package zhtt.biz01.web.controller;

import com.gitee.zhtt.entity.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zhtt.biz01.web.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping(value = "/api/user")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;
 
    @RequestMapping("/login")
    public JsonResponse login(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("loginUserId");
        User user = new User();
        user.setSessionId(session.getId());
        if(userId != null){
            user.setId(userId);
        }else{
            session.setAttribute("loginUserId", user.getId());
            redisTemplate.opsForValue().set("loginUser:" + user.getId(), session.getId());
        }
        return JsonResponse.success(user);
    }
 
    @RequestMapping(value = "/getUserInfo")
    public JsonResponse get(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = new User();
        user.setSessionId(session.getId());
        user.setId((String) session.getAttribute("loginUserId"));
        return JsonResponse.success(user);
    }
}
